import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:znmm/UI/utils/logger_service.dart';
import 'package:graphql_flutter/graphql_flutter.dart';

import '../UI/utils/my_global.dart';

typedef OperationSuccessCallback = void Function(Map<String, dynamic>? data);
typedef OperationErrorCallback = void Function(dynamic error);

class GraphQLService {
  static GraphQLClient initGraphQLClient(Link link) {
    return GraphQLClient(
      link: link,
      cache: GraphQLCache(),
    );
  }

  //-------------------------相当于get 查询是只读的操作 不会修改服务器上的数据
  static void performQuery(
    String query,
    Link link,
    OperationSuccessCallback onSuccess, {
    OperationErrorCallback? onError,
    bool bIsShowLoading = false,
    bool bShowRequest = false,
    bool bShowResponse = false,
    Map<String, dynamic> variables = const {},
  }) async {
    var connectivityResult = await Connectivity().checkConnectivity();
    if (connectivityResult == ConnectivityResult.none) {
      // 没有网络连接
      if (onError != null) {
        onError('No internet connection');
      }
      return;
    }

    // String tokenStr = 'token'; // 追加字段
//     String modifiedQuery = '''
//   query {
//     $tokenStr
//     $query
//   }
// ''';

//     String modifiedQuery = '''
//   $query {
//     $tokenStr
//   }
// ''';

    if (bShowRequest) {
      logger.d("********** 请求 Request Query**********\n"
          "time: ${DateTime.now()}\n"
          "query: $query");
    }

    final GraphQLClient client = initGraphQLClient(link);
    QueryOptions options =
        QueryOptions(document: gql(query), variables: variables);
    if (bIsShowLoading) {
      MyGlobal.showLoading();
    }
    try {
      QueryResult result = await client.query(options);
      if (bIsShowLoading) {
        MyGlobal.hideLoading();
      }
      if (result.hasException) {
        throw Exception('GraphQL Query Error: ${result.exception}');
      }

      if (bShowResponse) {
        logger.d("**********返回 Response Query**********\n"
            "time: ${DateTime.now()}\n"
            "data: ${prettyJson(result.data)}");
      }

      onSuccess(result.data);
    } catch (e) {
      if (bIsShowLoading) {
        MyGlobal.hideLoading();
      }
      print(e);
      if (onError != null) {
        onError(e);
      }
    }
  }

  //---------------------------------------相当于POST、PUT或DELETE, 会修改数据库
  static void performMutation(
    String mutation,
    Link link,
    OperationSuccessCallback onSuccess, {
    OperationErrorCallback? onError,
    bool bIsShowLoading = false,
  }) async {
    var connectivityResult = await Connectivity().checkConnectivity();
    if (connectivityResult == ConnectivityResult.none) {
      // 没有网络连接
      if (onError != null) {
        onError('No internet connection');
      }
      return;
    }

    // logger.d("**********请求 Request Mutation**********\n"
    //     "time: ${DateTime.now()}\n"
    //     "mutation: $mutation");

    final GraphQLClient client = initGraphQLClient(link);
    MutationOptions options = MutationOptions(document: gql(mutation));

    if (bIsShowLoading) {
      MyGlobal.showLoading(msg: "Loading...");
    }
    try {
      QueryResult result = await client.mutate(options);
      if (bIsShowLoading) {
        MyGlobal.hideLoading();
      }
      if (result.hasException) {
        throw Exception('GraphQL Mutation Error: ${result.exception}');
      }

      logger.d("**********返回 Response Mutation**********\n"
          "time: ${DateTime.now()}\n"
          "data: ${prettyJson(result.data)}");

      onSuccess(result.data);
    } catch (e) {
      if (bIsShowLoading) {
        MyGlobal.hideLoading();
      }
      print(e);
      if (onError != null) {
        onError(e);
      }
    }
  }
}
